const crypto = require('crypto');

// 封装 uni.showToast  
function showToast(message, duration = 2000, icon = 'none') {
	uni.showToast({
		title: message,
		icon: icon,
		duration: duration
	});
}

// 封装 uni.navigateTo  
function navigateTo(url, success, fail, complete) {
	uni.navigateTo({
		url: url,
		success: success,
		fail: fail,
		complete: complete
	});
}

//根据传入的时间戳和时间格式字符串返回对应时间字符串
function formatDate(timestamp, format) {
  const date = new Date(timestamp);
  const map = {
    'yyyy': date.getFullYear(),
    'MM': ('0' + (date.getMonth() + 1)).slice(-2),
    'dd': ('0' + date.getDate()).slice(-2),
    'HH': ('0' + date.getHours()).slice(-2),
    'mm': ('0' + date.getMinutes()).slice(-2),
    'ss': ('0' + date.getSeconds()).slice(-2),
  };

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(match) {
    return map[match];
  });
}

//MD5加密

function md5Encrypt(text) {
    return crypto.createHash('md5').update(text).digest('hex');
}

//传入视频获取封面
function getVideoFrame(url, seekTime = 0.5) {
  return new Promise((resolve, reject) => {
    // 判断是否为图片 URL
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    const urlExtension = url.split('.').pop().toLowerCase();

    if (imageExtensions.includes(urlExtension)) {
      resolve(url); // 如果是图片 URL，直接返回
      return;
    }

    const video = document.createElement('video');

    video.src = url;
    video.crossOrigin = 'anonymous'; // If the video is from a different origin, set crossOrigin to 'anonymous'

    video.addEventListener('loadeddata', () => {
      video.currentTime = seekTime;
    });

    video.addEventListener('seeked', () => {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      const context = canvas.getContext('2d');
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      canvas.toBlob(blob => {
        const url = URL.createObjectURL(blob);
        resolve(url);
      }, 'image/jpeg');
    });

    video.addEventListener('error', (e) => {
      reject(e);
    });
  });
}

// 导出这两个函数  
export default {
	showToast,
	navigateTo,
	formatDate,
	md5Encrypt,
	getVideoFrame
};